<!--  -->
<template>

  <div class="wrap-manager" v-loading.lock="loading">

    <div class="diviling_line option">
      <div class="diviling_block">
        <div class="block_icon">
          <div class="icon"></div>
        </div>
        <div class="label">基础信息</div>
      </div>
    </div>

    <div class="base_content">
      <el-form :model="userEditModel" :inline="true" ref="userForm" class="demo-form-inline" label-width="100px"
        :rules="rules">
        <el-form-item label="用户姓名" prop="name">
          <el-input v-model="userEditModel.name" placeholder="请输入用户姓名"></el-input>
        </el-form-item>
        <!-- <el-form-item label="用户编码" prop="code">
          <el-input v-model="userEditModel.code" placeholder="请输入用户编码"></el-input>
        </el-form-item> -->
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="userEditModel.nickName" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="userEditModel.phone" placeholder="请输入联系方式" @blur="phoneChange"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop= "positionKeys">
            <el-select v-model="userEditModel.positionKeys" clearable filterable>
                <el-option v-for="item in positionList" :key="item.positionPrimaryKey" :label="item.name" :value="item.positionPrimaryKey"></el-option>
            </el-select>
        </el-form-item> 
        <el-form-item label="Email" prop="email">
          <el-input v-model="userEditModel.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" :rows="2" v-model="userEditModel.remark" placeholder="备注"></el-input>
        </el-form-item>
        <div class="diviling_line option">
          <div class="diviling_block">
            <div class="block_icon">
              <div class="icon"></div>
            </div>
            <div class="label">密码设置</div>
          </div>
        </div>
        <el-form-item label="登录账户" prop="acccount">
          <el-input v-model="userEditModel.account" placeholder="登录账户为输入手机号" disabled></el-input>
        </el-form-item>
        <br>
        <el-form-item label="密码" prop="passWord" v-if="!isEdit">
          <el-input type="password" v-model="userEditModel.passWord" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="原密码" prop="passwordOld" v-if="isEdit">
          <el-input type="password" v-model="userEditModel.passwordOld" placeholder="请输入原密码" show-password></el-input>
        </el-form-item>
        <br>
        <el-form-item label="新密码" prop="passwordNew" style="margin-top:10px;" v-if="isEdit">
          <el-input type="password" v-model="userEditModel.passwordNew" placeholder="请输入新密码" show-password></el-input>
        </el-form-item>
        <br>
        <el-form-item label="确认密码" prop="checkPassWord" style="margin-top:10px;" v-if="isEdit">
            <el-input type="password" v-model="userEditModel.checkPassWord" placeholder="请再次输入密码"
              show-password></el-input>
        </el-form-item>
      </el-form>
    </div>
    <div class="option_list">
      <div class="option_content">
        <el-button @click="submit" type="primary" plain>保存</el-button>
      </div>
    </div>
  </div>
</template>

<style lang='less' scoped>
.wrap-manager {
  text-align: left;
  padding: 5px 20px;

  .base_content {
    //background-color: #ededed;
    margin: 10px auto;
    padding: 10px 10px;
    font-size: 0.9rem;
    line-height: 2rem;
  }

  .content {
    margin: 10px auto;
  }
}
</style>
<script>
let validatePass = (rule, value, callback) => {
  if (value === '') {
    return callback();
  } else {
    let reg = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,.\/]).{6,16}$/;
    if (!reg.test(value)) {
      return callback(new Error('密码长度为6-16个字符，必须包含英文、数字、特殊字符'));
    } else {
      return callback()
    }
  }

}
let isEmpty = (value) => {
  if (!value || value.length == 0) {
    return true;
  }
  return false;
}
import {
  ElMessage
} from 'element-plus'
import phoneRegionUtil from '@/utils/phoneRegionUtil'
import { addUser, updateUser, updateUserPassword, getStationList } from '@/api/user.js';
export default {
  components: {},
  props: {
    user: {
      type: Object,
      default: () => {
        return {}
      }
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      userEditModel: {
        name: '',
        code: '',
        nickName: '',
        phone: '',
        email: '',
        remark: '',
        account: '',
        passWord: '',
        passwordOld: '',
        passwordNew: '',
        checkPassWord: '',
        userPrimaryKey: '',
        positionKeys: []
      },
      positionList: [],
      modifyPassWordShow: false,
      rules: {
        name: [
          { required: true, message: "请输入部门名称", trigger: "blur" },
        ],
        nickName: [
          { required: true, message: "请输入昵称", trigger: "blur" },
        ],
        positionKeys: [
        { required: true, message: "请选择部门", trigger: "blur" },
        ],
        phone: [
          {
            required: true, trigger: "blur", validator: (rule, value, callback) => {
              let result = phoneRegionUtil.getPhoneRegion(value)
              if (result == 'Unknown') {
                return callback(new Error('请输入合法的联系方式'));
              }
              return callback()
            }
          },
        ],
        passWord: [
          { validator: validatePass, trigger: "blur" },
        ],
        passwordNew: [
          {
            validator: (rule, value, callback) => {
              let reg = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,.\/]).{6,16}$/;
              if (value == '' && (this.userEditModel.passwordOld !== '' || this.userEditModel.checkPassWord !== '')) {
                return callback(new Error('请输入新密码'));
              } else {
                if (value == '') {
                  return callback();
                } else if (!reg.test(value)) {
                  return callback(new Error('密码长度为6-16个字符，必须包含英文、数字、特殊字符'));
                } else {
                  return callback();
                }
              }
            }, trigger: "blur"
          },
        ],
        passwordOld: [
          {
            validator: (rule, value, callback) => {
              if (value === '' && (this.userEditModel.passwordNew !== '' || this.userEditModel.checkPassWord !== '')) {
                return callback(new Error('请输入原密码'));
              } else {
                let reg = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,.\/]).{6,16}$/;
                if (value == '') {
                  return callback()
                }
                else if (!reg.test(value)) {
                  return callback(new Error('密码长度为6-16个字符，必须包含英文、数字、特殊字符'));
                } else {
                  return callback()
                }
              }
            }, trigger: "blur"
          },
        ],
        checkPassWord: [
          {
            validator: (rule, value, callback) => {
              if (value == '' && this.userEditModel.passwordOld == '' && this.userEditModel.passwordNew == '') {
                return callback();
              } else {
                if (value == '') {
                  return callback(new Error('请输入确认密码'));
                } else if (value !== this.userEditModel.passwordNew) {
                  return callback(new Error('两次输入密码不一致!'));
                } else {
                  return callback()
                }
              }
            },
            trigger: "blur"
          }
        ],
      }
    };
  },
  computed: {},
  watch: {},
  methods: {
    submit() {
      this.$refs.userForm.validate(async (valid) => {
        let eidtUserObj = {
          "account": "",
          "email": "",
          "name": "",
          "nickName": "",
          "passWord": "",
          "phone": "",
          "userPrimaryKey": "",
          "corpKey": "123",
          "positionKeys": []
        }
        if (valid) {
          for (var key in eidtUserObj) {
            eidtUserObj[key] = this.userEditModel[key] || eidtUserObj[key]
          }
          eidtUserObj.positionKeys = [eidtUserObj.positionKeys]
          if (this.isEdit) {
            eidtUserObj.updatePosition = true
            delete eidtUserObj.passWord
            let self = this
            let updateUserFuc = async function () {
              let res = await updateUser(eidtUserObj)
              let resp = res.data
              if (resp && resp.success) {
                ElMessage.success("更新用户成功！")
                self.saveSuccess()
              } else {
                ElMessage.error(`更新用户失败，错误：${resp.message}`)
              }
            }
            if (this.userEditModel.passwordOld !== '') {
              let {passwordNew,passwordOld,userPrimaryKey} = this.userEditModel
              let passWordObj = {
                passwordNew,passwordOld,userPrimaryKey
              }
              let res = await updateUserPassword(passWordObj)
              let resp = res.data
              if (resp && resp.success) {
                updateUserFuc()
              } else {
                ElMessage.error(`错误：${resp.message}`)
              }
            } else {
              updateUserFuc()
            }
          } else {
            let res = await addUser(eidtUserObj)
            let resp = res.data
            if (resp && resp.success) {
              ElMessage.success("添加用户成功！")
              this.saveSuccess()
            } else {
              ElMessage.error(`添加用户失败，错误：${resp.message}`)
            }
          }
        }
      })

    },
    phoneChange() {
      this.userEditModel.account = this.userEditModel.phone
    },
    saveSuccess() {
      this.$emit('closeDrawer')
    }
  },
  created() {
    if (this.isEdit) {
      for (var key in this.user) {
        this.userEditModel[key] = this.user[key]
      }
    }
    this.userEditModel.positionKeys =  this.userEditModel.positionKeys[0] || ''
    console.log(  this.userEditModel,this.user)
    this.loading = true
    getStationList().then(res=>{
      this.loading = false
      if(res.data.success){
        this.positionList = res.data.rows
      }
    })
  },
  mounted() {

  },
}
</script>